package com.zbkj.admin.boot.servlet.context;

import com.zbkj.admin.boot.context.MicaContextProperties;
import com.zbkj.admin.boot.context.MicaHttpHeadersGetter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import net.dreamlu.mica.core.utils.StringUtil;
import net.dreamlu.mica.core.utils.WebUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;

import java.util.List;

/**
 * HttpHeaders 获取器
 *
 * @author L.cm
 */
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class ServletHttpHeadersGetter implements MicaHttpHeadersGetter {
	private final MicaContextProperties properties;

	@Nullable
	@Override
	public HttpHeaders get() {
		HttpServletRequest request = WebUtil.getRequest();
		if (request == null) {
			return null;
		}
		return get(request);
	}

	public HttpHeaders get(HttpServletRequest request) {
		HttpHeaders headers = new HttpHeaders();
		List<String> crossHeaders = properties.getCrossHeaders();
		// 传递请求头
		for (String crossHeaderName : crossHeaders) {
			String headerValue = request.getHeader(crossHeaderName);
			if (StringUtil.isNotBlank(headerValue)) {
				headers.add(crossHeaderName, headerValue);
			}
		}
		return headers;
	}

}
